"""
邮件配置模块
配置FastAPI-Mail邮件发送服务
"""

from typing import List, Optional
from pydantic import BaseModel, EmailStr
from fastapi_mail import ConnectionConfig, FastMail
from pathlib import Path

from app.core.config import settings
from app.core.logging import get_logger

logger = get_logger(__name__)


class EmailSettings(BaseModel):
    """邮件配置"""
    MAIL_USERNAME: str = "18967498922@163.com"
    MAIL_PASSWORD: str = "SRZm93BNAXKzX82s"  # 授权码
    MAIL_FROM: EmailStr = "18967498922@163.com"
    MAIL_FROM_NAME: str = "FastAPI Platform"
    MAIL_PORT: int = 587
    MAIL_SERVER: str = "smtp.163.com"
    MAIL_STARTTLS: bool = True
    MAIL_SSL_TLS: bool = False
    USE_CREDENTIALS: bool = True
    VALIDATE_CERTS: bool = True
    
    # 模板配置
    TEMPLATE_FOLDER: Path = Path(__file__).parent.parent / "templates" / "email"


# 全局邮件设置实例
email_settings = EmailSettings()

# FastAPI-Mail连接配置
mail_config = ConnectionConfig(
    MAIL_USERNAME=email_settings.MAIL_USERNAME,
    MAIL_PASSWORD=email_settings.MAIL_PASSWORD,
    MAIL_FROM=email_settings.MAIL_FROM,
    MAIL_FROM_NAME=email_settings.MAIL_FROM_NAME,
    MAIL_PORT=email_settings.MAIL_PORT,
    MAIL_SERVER=email_settings.MAIL_SERVER,
    MAIL_STARTTLS=email_settings.MAIL_STARTTLS,
    MAIL_SSL_TLS=email_settings.MAIL_SSL_TLS,
    USE_CREDENTIALS=email_settings.USE_CREDENTIALS,
    VALIDATE_CERTS=email_settings.VALIDATE_CERTS,
    TEMPLATE_FOLDER=email_settings.TEMPLATE_FOLDER,
)

# 创建FastMail实例
fast_mail = FastMail(mail_config)


def get_mail_client() -> FastMail:
    """获取邮件客户端实例"""
    return fast_mail


class EmailTemplate:
    """邮件模板枚举"""
    WELCOME = "welcome.html"
    NOTIFICATION = "notification.html"
    USER_MESSAGE = "user_message.html"
    PASSWORD_RESET = "password_reset.html"
    VERIFICATION = "verification.html"


class EmailPriority:
    """邮件优先级"""
    LOW = 1
    NORMAL = 2
    HIGH = 3
    URGENT = 4


def validate_email_config() -> bool:
    """验证邮件配置"""
    try:
        # 检查必要的配置项
        required_fields = [
            email_settings.MAIL_USERNAME,
            email_settings.MAIL_PASSWORD,
            email_settings.MAIL_SERVER,
            email_settings.MAIL_PORT
        ]
        
        if not all(required_fields):
            logger.error("邮件配置不完整")
            return False
        
        # 检查模板文件夹
        if not email_settings.TEMPLATE_FOLDER.exists():
            logger.warning(f"邮件模板文件夹不存在: {email_settings.TEMPLATE_FOLDER}")
            # 创建模板文件夹
            email_settings.TEMPLATE_FOLDER.mkdir(parents=True, exist_ok=True)
            logger.info(f"已创建邮件模板文件夹: {email_settings.TEMPLATE_FOLDER}")
        
        logger.info("✅ 邮件配置验证成功")
        return True
        
    except Exception as e:
        logger.error(f"邮件配置验证失败: {e}")
        return False